﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using DailyRssDownload.Lib;
using System.Threading;
using System.Runtime.InteropServices;

namespace DailyRssDownload.UI {
    static class Program {
		[DllImport("kernel32.dll")]
		static extern bool AttachConsole(int dwProcessId);
		[DllImport("kernel32.dll")]
		static extern bool FreeConsole();
		const int ATTACH_PARENT_PROCESS = -1;
		public struct KEYDBINPUT {
			public Int16 wVk;
			public Int16 wScan;
			public Int32 dwFlags;
			public Int32 time;
			public Int32 dwExtraInfo;
			public Int32 __filler1;
			public Int32 __filler2;
		}

		public struct INPUT {
			public Int32 type;
			public KEYDBINPUT ki;
		}

		[DllImport("user32")]
		public static extern int SendInput(int cInputs, ref INPUT pInputs, int cbSize);

		/// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main() {
			string[] args = Environment.GetCommandLineArgs();

			if (args.Length <= 1) {
				Application.EnableVisualStyles();
				Application.SetCompatibleTextRenderingDefault(false);
				Application.Run(new DailyRssDownloadSettings());
			} else {
				AttachConsole(ATTACH_PARENT_PROCESS);
				Console.WriteLine("");
				Console.WriteLine("");

				if (args[1].ToLower() == "downloadnow") {
					DownloadNow();
				} else {
					Console.WriteLine("Unexpected argument.  DailyRssDownload.exe usage: DailyRssDownload DownloadNow");
				}

				ReleaseConsole();
			}
        }

		private static void DownloadNow() {
			try {
				Console.WriteLine("Starting Download.");

				Settings objSettings = new Settings();
				Newspaper objConnection = new Newspaper(objSettings);
				objConnection.DownloadNow();

				Console.WriteLine("Download Successful.");
			} catch (Exception ex) {
				Console.WriteLine("An error occurred:");
				Console.WriteLine(ex.ToString());
			}
		}

		static void ReleaseConsole() {
			FreeConsole();
			// simulate return pressing
			INPUT input = new INPUT();
			input.type = 1; // INPUT_KEYBOARD
			input.ki.wVk = 0x0D; // VK_RETURN
			SendInput(1, ref input, Marshal.SizeOf(input));
			input.ki.dwFlags = 2; // KEYEVENTF_KEYUP
			SendInput(1, ref input, Marshal.SizeOf(input));
		}
    }
}
